package com.huawei.esdk.uc.u19.business.professional.rest.common;

import java.util.List;
import java.util.Map;
import org.apache.log4j.Logger;
import com.huawei.esdk.platform.callback.itf.ICallback;
import com.huawei.esdk.platform.common.SDKErrorCode;
import com.huawei.esdk.platform.common.exception.SDKException;
import com.huawei.esdk.platform.nemgr.base.NotifyCollector;
import com.huawei.esdk.uc.base.UCNotifyCallback;
import com.huawei.esdk.uc.domain.model.Notify;
import com.huawei.esdk.uc.domain.util.u19.U19Utils;
import com.huawei.esdk.uc.u19.business.professional.rest.ctc.callback.RestNotifyCTCCallback;

public class U19RestCallbackRegisterService
{
    private static final Logger LOGGER = Logger.getLogger(U19RestCallbackRegisterService.class);
    
    private NotifyCollector notifyCollector;
    
    private UCNotifyCallback ucNotifyCallback = new UCNotifyCallback();
    
    private String u19DeviceId = U19Utils.getU19DeviceId();
    
    public SDKErrorCode register(Map<String, String> map)
    {
        notifyCollector.subscribeNotify(u19DeviceId, "_", ucNotifyCallback);
        
        for (Map.Entry<String, String> entry : map.entrySet())
        {
            if ("CTC".equalsIgnoreCase(entry.getKey()))
            {
                ICallback callback = new RestNotifyCTCCallback(entry.getValue());
                ucNotifyCallback.registerCallback("ctc", callback);
            }
            else
            {
                LOGGER.warn("UCRestCallbackRegisterService register ability error - " + entry.getKey()
                    + " is not supported");
            }
        }
        SDKErrorCode result = new SDKErrorCode();
        try
        {
            result = new Notify().registerNotification4U19(true);
        }
        catch (SDKException e)
        {
            LOGGER.debug("register eror!");
        }
        return result;
    }
    
    public SDKErrorCode unregister(List<String> modules)
    {
        // unSubscribe until all modules are unSubscribed
        for (String module : modules)
        {
            ucNotifyCallback.unregisterCallback(module);
        }
        
        //call south interface
        if (!ucNotifyCallback.hasRegisteredModule())
        {
            notifyCollector.unsubscribeNotify(u19DeviceId, "_");
        }
        
        SDKErrorCode result = new SDKErrorCode();
        try
        {
            result = new Notify().registerNotification4U19(false);
        }
        catch (SDKException e)
        {
            LOGGER.debug("unregister error!");
        }
        return result;
    }
    
    public NotifyCollector getNotifyCollector()
    {
        return notifyCollector;
    }
    
    public void setNotifyCollector(NotifyCollector notifyCollector)
    {
        this.notifyCollector = notifyCollector;
    }
}
